/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

function isblank(s) {
    for(var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
    }
    return true;
}

String.prototype.stripBR = function (){
    var matchTag = /<br>/g;
    return this.replace(matchTag,'\n');
}

String.prototype.stripOthers = function (){
    var matchTag = /<([^>]+)>/g;
    return this.replace(matchTag,'');
}

function getGrammar(){
    var textoGram=null;
    var iframe = document.getElementById('gramArea').contentDocument;
    if(iframe.getElementById('myPRE') != null){
        textoGram = iframe.getElementById('myPRE').innerHTML;
        textoGram = textoGram.stripBR();
        textoGram = textoGram.stripOthers();
    }
    //alert(textoGram);
    return textoGram;
}


Ext.onReady(function(){

    var win;
    var textoGram;
    var subs;
    var newImg;

    function clear()
    {
        document.getElementById('nterms').innerHTML= 0;
        document.getElementById('terms').innerHTML= 0;
        document.getElementById('prods').innerHTML= 0;
        document.getElementById('uprods').innerHTML= 0;
        document.getElementById('rec').innerHTML= 0;
        document.getElementById('rhs').innerHTML= 0;
        document.getElementById('alts').innerHTML= 0;
        document.getElementById('rd').innerHTML= 0;
        document.getElementById('ll1').innerHTML= 0;

        document.getElementById('pnterms').innerHTML= 0;
        document.getElementById('pterms').innerHTML= 0;
        document.getElementById('pprods').innerHTML= 0;
        document.getElementById('puprods').innerHTML= 0;
        document.getElementById('prec').innerHTML= 0;
        document.getElementById('prhs').innerHTML= 0;
        document.getElementById('palts').innerHTML= 0;
        document.getElementById('prd').innerHTML= 0;
        document.getElementById('pll1').innerHTML= 0;

        document.getElementById('inhatrbs').innerHTML= 0;
        document.getElementById('nullsymbs').innerHTML= 0;
        document.getElementById('uselesssymbs').innerHTML= 0;
        document.getElementById('nonreachsymbs').innerHTML= 0;

    }

    function check_grammar()
    {
        var res;
        textoGram = getGrammar();
        if(textoGram != null && !isblank(textoGram))
        {
        var conn = new Ext.data.Connection();
        conn.request({
            url : 'checkgrammar.jsp' ,
            params : {text : textoGram},
            method: 'GET',
            success: function ( result, request ) {
                    //Ext.MessageBox.alert('Success', result.responseText);
                    var json = Ext.util.JSON.decode(result.responseText);

                    if(json.errors == "0")
                    {
                        Ext.MessageBox.alert('Success', 'The grammar is correct!');
                    }
                    else
                    {
                        Ext.MessageBox.alert('Failed', 'The grammar has '+ json.errors +' syntax errors!');
                    }
                },
                failure: function ( result, request) {
                    Ext.MessageBox.alert('Failed', result.responseText);
                }
            });

        }
        else
        {
            Ext.MessageBox.alert('Failed', 'The grammar is empty!');
        }


        
    }

    function check_grammar_seman()
    {
        var res;
        //textoGram = document.getElementById('gramArea').value;

        textoGram = getGrammar();
        if(textoGram != null && !isblank(textoGram))
        {
        var conn = new Ext.data.Connection();
        conn.request({
            url : 'checkgrammarseman.jsp' ,
            params : {text : textoGram},
            method: 'GET',
            success: function ( result, request ) {
                    //Ext.MessageBox.alert('Success', result.responseText);
                    var json = Ext.util.JSON.decode(result.responseText);
                    
                    if(json.success )
                    {
                       Ext.MessageBox.alert('Success', 'The grammar is correct!');
                    }
                    else
                    {
                        var errs ="";

                        for(i=0 ; i<json.errors.length ; i++ ) {errs +=  "\n\t-"+json.errors[i];}

                        alert('The following symbols are not defined :' + errs);
                    }
            },
            failure: function ( result, request) {
                    Ext.MessageBox.alert('Failed', result.responseText);
            }
        });
        }else{
            Ext.MessageBox.alert('Failed', 'The grammar is empty!');
        }
    }

    function rup()
    {
        //textoGram = document.getElementById('gramArea').value;
        textoGram = getGrammar();
        if(textoGram != null && !isblank(textoGram))
        {
        Ext.Ajax.request({
            url : 'removeUnitProd.jsp' ,
            params : {text : textoGram},
            method: 'GET',
            success: function ( result, request ) {
                var json = Ext.util.JSON.decode(result.responseText);
                if(json.success)
                {
                    var iframe = document.getElementById('gramArea').contentWindow;
                    while (iframe.document.body.hasChildNodes()) {
                        iframe.document.body.removeChild(iframe.document.body.firstChild);
                    }
                    iframe.document.body.innerHTML=json.rup;
                    iframe.CodePress.syntaxHighlight('generic');
                }
                else
                {
                    Ext.MessageBox.alert('Failed', 'The grammar has syntax errors!');
                }

            },
            failure: function ( result, request) {
                    Ext.MessageBox.alert('Failed', result.responseText);
            }
        });
        }else{
            Ext.MessageBox.alert('Failed', 'The grammar is empty!');
        }
    }

    function fun()
    {
        //textoGram = document.getElementById('gramArea').value;
        textoGram = getGrammar();
        if(textoGram != null && !isblank(textoGram))
        {
        Ext.Ajax.request({
            url : 'getfuns.jsp' ,
            params : {text : textoGram},
            method: 'GET',
            success: function ( result, request ) {
                var json = Ext.util.JSON.decode(result.responseText);
                if(json.success)
                {
                    var img = json.img;
                    img = "data:image/gif;base64,"+img;
                    //document.getElementById('funs').src = img;
                    windowFun(img);
                }
                else
                {
                    Ext.MessageBox.alert('Failed', 'The grammar has syntax errors!');
                }

            },
            failure: function ( result, request) {
                    Ext.MessageBox.alert('Failed', result.responseText);
            }
        });
        }else{
            Ext.MessageBox.alert('Failed', 'The grammar is empty!');
        }

    }

    function get_metrics()
    {
        //textoGram = document.getElementById('gramArea').value;
        textoGram = getGrammar();
        if(textoGram != null && !isblank(textoGram))
        {
        Ext.Ajax.request({
            url : 'getmetrics.jsp' ,
            params : {text : textoGram},
            method: 'GET',
            success: function ( result, request ) {
                var json = Ext.util.JSON.decode(result.responseText);

                if(json.success)
                {
                    document.getElementById('nterms').innerHTML= json.nterms;
                    document.getElementById('terms').innerHTML= json.terms;
                    document.getElementById('prods').innerHTML= json.prods;
                    document.getElementById('uprods').innerHTML= json.uprods;
                    document.getElementById('rec').innerHTML= json.recs;
                    document.getElementById('rhs').innerHTML= json.rhs;
                    document.getElementById('alts').innerHTML= json.alts;
                    document.getElementById('rd').innerHTML= json.rd;
                    document.getElementById('ll1').innerHTML= json.ll1;
                    document.getElementById('synatrbs').innerHTML= json.synatribs;
                    document.getElementById('inhatrbs').innerHTML= json.inhatribs;
                    document.getElementById('nullsymbs').innerHTML= json.nullsymbs.length;
                    document.getElementById('uselesssymbs').innerHTML= json.uselesssymbs.length;
                    document.getElementById('nonreachsymbs').innerHTML= json.nonreachsymbs.length;

                    if(json.nullsymbs.length > 0 || json.uselesssymbs.length > 0 || json.nonreachsymbs.length > 0)
                    {
                        var nulls = 'The following symbols are nullable :';
                        var usells = 'The following symbols are useless :';
                        var nonreach = 'The following symbols are not reachable :';

                        var message = "";

                        for(i=0 ; i<json.nullsymbs.length ; i++ ) {nulls +=  " "+json.nullsymbs[i];}
                        for(i=0 ; i<json.uselesssymbs.length ; i++ ) {usells +=  " "+json.uselesssymbs[i];}
                        for(i=0 ; i<json.nonreachsymbs.length ; i++ ) {nonreach +=  " "+json.nonreachsymbs[i];}
                        
                        if(json.nullsymbs.length > 0){message += nulls + "<br /> <br />"}
                        if(json.uselesssymbs.length > 0){message += usells + "<br /> <br />"}
                        if(json.nonreachsymbs.length > 0){message += nonreach + "<br />"}

                        Ext.MessageBox.alert('Metrics',message);
                        //alert('The following symbols are nullable :' + nulls);
                    }

                }
                else
                {
                    Ext.MessageBox.alert('Failed', 'The grammar has syntax errors!');
                }
                    
            },
            failure: function ( result, request) {
                    Ext.MessageBox.alert('Failed', result.responseText);
            }
        });
        }else{
            Ext.MessageBox.alert('Failed', 'The grammar is empty!');
        }
    }

    function metricsRUP()
    {
        //textoGram = document.getElementById('gramArea').value;
        textoGram = getGrammar();
        if(textoGram != null && !isblank(textoGram))
        {
        Ext.Ajax.request({
            url : 'getmetricsRUP.jsp' ,
            params : {text : textoGram},
            method: 'GET',
            success: function ( result, request ) {
                var json = Ext.util.JSON.decode(result.responseText);

                if(json.success)
                {
                    document.getElementById('pnterms').innerHTML= json.nterms;
                    document.getElementById('pterms').innerHTML= json.terms;
                    document.getElementById('pprods').innerHTML= json.prods;
                    document.getElementById('puprods').innerHTML= json.uprods;
                    document.getElementById('prec').innerHTML= json.recs;
                    document.getElementById('prhs').innerHTML= json.rhs;
                    document.getElementById('palts').innerHTML= json.alts;
                    document.getElementById('prd').innerHTML= json.rd;
                    document.getElementById('pll1').innerHTML= json.ll1;
                }
                else
                {
                    Ext.MessageBox.alert('Failed', 'The grammar has syntax errors!');
                }

            },
            failure: function ( result, request) {
                    Ext.MessageBox.alert('Failed', result.responseText);
            }
        });
        }else{
            Ext.MessageBox.alert('Failed', 'The grammar is empty!');
        }
    }

    function subFunc()
    {
        textoGram = getGrammar();
        var oldS = document.getElementById('oldS').value;
        var newS = document.getElementById('newS').value;

        Ext.Ajax.request({
            url : 'substitute.jsp' ,
            params : {text : textoGram , oldS : oldS , newS : newS},
            method: 'GET',
            success: function ( result, request ) {
                var json = Ext.util.JSON.decode(result.responseText);

                if(json.success)
                {
                    //document.getElementById('gramArea').innerHTML= json.subs;
                    var iframe = document.getElementById('gramArea').contentWindow;
                    while (iframe.document.body.hasChildNodes()) {
                        iframe.document.body.removeChild(iframe.document.body.firstChild);
                    }
                    iframe.document.body.innerHTML=json.subs;
                    iframe.CodePress.syntaxHighlight('generic');
                    subs.hide();
                }
                else
                {
                    Ext.MessageBox.alert('Failed', json.error);
                }
                

            },
            failure: function ( result, request) {
                    Ext.MessageBox.alert('Failed', result.responseText);
            }
        });
    }

    function substitute()
    {
        if(!subs){
           subs = new Ext.Window({
                    minimizable: true,
                    maximizable: true,
                    closable:true,
                    title:'Substitute',
                    closeAction:'hide',
                    layout: 'absolute',
                    height: 150,
                    width: 500,
                    items:[fpS]
                });
           }
        subs.show();
    }

    function window()
    {
       if(!win){
       win = new Ext.Window({
                minimizable: true,
                maximizable: true,
                closable:true,
                title:'Open file...',
                closeAction:'hide',
                layout: 'absolute',
                height: 150,
                width: 500,
                items:[fp]
            });
       }
        win.show();
    }

    function windowFun(src)
    {
        newImg = new Image();
        newImg.src = src;

        var height = 600;
        var width  = 800;

        if( newImg.height + 40 < 600 || newImg.width + 20 < 800 )
        {
        height = newImg.height + 40;
        width = newImg.width + 20;
        }

        newImg.src = src;
        var funs = new Ext.Window({
                minimizable: true,
                maximizable: true,
                closable:true,
                title:'Funs',
                closeAction:'hide',
                layout: 'absolute',
                autoScroll: true,
                height: height,
                width: width,
                html:'<img id="funs" border="0" style="overflow:scroll;" align="middle" src="'+src+'"/>' //,
               
            });
            funs.show();

    }

    var action = new Ext.Action({
        text: 'Open File...',
        handler: function(){
            window();
        }
    });

    var fpS = new Ext.FormPanel({
        monitorValid:true,
        height: 200,
        width: 500,
        frame: true,
        autoHeight: true,
        bodyStyle: 'padding: 10px 10px 0 10px;',
        labelWidth: 90,
        defaultType:'textfield',
        defaults: {
            anchor: '95%',
            allowBlank: false,
            msgTarget: 'side'
        },
        items: [{

            xtype: 'textfield',
            inputType: 'text',
            fieldLabel: 'Old Symbol',
            id: 'oldS'
        },{

            xtype: 'textfield',
            inputType: 'text',
            fieldLabel: 'New Symbol',
            id: 'newS'
        }
        ],buttons: [{
            text: 'OK',
            handler: function(){
                if(fpS.getForm().isValid())
                {
	         subFunc();
                }
           }
        },{
            text: 'Reset',
            handler: function(){
                fpS.getForm().reset();
            }
        }]

    });
    
    var fp = new Ext.FormPanel({
        fileUpload: true,
        url: "file-upload.jsp",
        method: 'POST',
        monitorValid:true,
        height: 150,
        width: 500,
        frame: true,
        title: 'File Upload Form',
        autoHeight: true,
        bodyStyle: 'padding: 10px 10px 0 10px;',
        labelWidth: 50,
        defaultType:'textfield',
        defaults: {
            anchor: '95%',
            allowBlank: false,
            msgTarget: 'side'
        },
        items: [{
                
            xtype: 'textfield',
            inputType: 'file',
            emptyText: 'Select a file',
            fieldLabel: 'File',
            name: 'filep',
            buttonText: ''
        }],
        buttons: [{
            text: 'Open',
            handler: function(){

                if(fp.getForm().isValid()){
	         fp.getForm().submit({
	                   
	                    waitMsg: 'Uploading your file...',
	                    success: function(fp,request){
                                textoGram = request.result.file;
                                clear();
                                var iframe = document.getElementById('gramArea').contentWindow;
                                while (iframe.document.body.hasChildNodes()) {
                                    iframe.document.body.removeChild(iframe.document.body.firstChild);
                                }
                                iframe.document.body.innerHTML=textoGram;
                                iframe.CodePress.syntaxHighlight('init');
	                        win.hide();
	                    }
	                });
                }

            }
        },{
            text: 'Reset',
            handler: function(){
                fp.getForm().reset();
            }
        }]
    });


    var tb = new Ext.Toolbar({
        renderTo: document.body,
        height : 60,
        text:'Menus',
        items :[{
         text:'File',
         menu: [action]  // assign menu by instance
        },{
            text:'Check Syntax',
            handler: function(){
                check_grammar();
            }
        },{
            text:'Check Semantic',
            handler: function(){
                check_grammar_seman();
            }
        },
        {
            text:'Calculate Metrics',
            handler: function(){
                get_metrics();
            }
        },{
            text:'Remove Unitary Productions',
            handler: function(){
                rup();
            }
        },{
            text:'Fan IN & Fan OUT',
            handler: function(){
                fun();
            }
        },{
            text:'Predictable Metrics with UPR',
            handler: function(){
                metricsRUP();
            }
        },{
            text:'Substitute',
            handler: function(){
               
                    substitute();
          }
        }
    ]
   });

   var metrics = new Ext.FormPanel({
        labelWidth: 100, // label settings here cascade unless overridden
        frame:true,
        bodyStyle:'padding:0 5px 0',
        width : '100%',
        height : '100%',
        title : "Metrics",
        items: [{
            layout:'column',
            items:[{
                    columnWidth:.5,
                    layout: 'form',
                    defaultType: 'displayfield',
                    defaults: {width: 100,height: 30,value: '0'},
                    items: [
                        {
                            fieldLabel: 'Terminals',
                            id: 'terms'
                        },{
                            fieldLabel: 'Non Terminals',
                            id: 'nterms'
                        },{
                            fieldLabel: 'Productions',
                            id: 'prods'
                        }, {
                            fieldLabel: 'Unitary Productions',
                            id: 'uprods'
                        }, {
                            fieldLabel: 'Recursivity',
                            id: 'rec'
                        },{
                        fieldLabel: 'RHS',
                        id: 'rhs'
                    },{
                        fieldLabel: 'Alternatives',
                        id: 'alts'
                    }
                    ]

            }, {
                    columnWidth:.5,
                    layout: 'form',
                    defaultType: 'displayfield',
                    defaults: {width: 100,height: 30,value: '0'},
                    items: [
                      {
                        fieldLabel: 'RD Size',
                        id: 'rd'
                    }, {
                        fieldLabel: 'LL1 Size',
                        id: 'll1'
                    }, {
                        fieldLabel: 'Syn Atribs',
                        id: 'synatrbs'
                    },
                    {
                        fieldLabel: 'Inh Atribs',
                        id: 'inhatrbs'
                    },
                    {
                        fieldLabel: 'Nullable Symbs',
                        id: 'nullsymbs'
                    }
                    , {
                        fieldLabel: 'Useless Symbs',
                        id: 'uselesssymbs'
                    }, {
                        fieldLabel: 'Nonreachable Symbs',
                        id: 'nonreachsymbs'
                    }
            ]
            }]
        }]
    });

    var metricsPred = new Ext.FormPanel({
        labelWidth: 100, // label settings here cascade unless overridden
        frame:true,
        bodyStyle:'padding:0 5px 0',
        width : '100%',
        height : '100%',
        title : "Predictable Metrics with UPR",
        items: [{
            layout:'column',
            items:[{
                    columnWidth:.5,
                    layout: 'form',
                    defaultType: 'displayfield',
                    defaults: {width: 100,height: 30,value: '0'},
                    items: [
                        {
                            fieldLabel: 'Terminals',
                            id: 'pterms'
                        },{
                            fieldLabel: 'Non Terminals',
                            id: 'pnterms'
                        },{
                            fieldLabel: 'Productions',
                            id: 'pprods'
                        }, {
                            fieldLabel: 'Unitary Productions',
                            id: 'puprods'
                        }, {
                            fieldLabel: 'Recursivity',
                            id: 'prec'
                        }
                    ]

            }, {
                    columnWidth:.5,
                    layout: 'form',
                    defaultType: 'displayfield',
                    defaults: {width: 100,height: 30,value: '0'},
                    items: [
                    {
                        fieldLabel: 'RHS',
                        id: 'prhs'
                    }, {
                        fieldLabel: 'Alternatives',
                        id: 'palts'
                    }, {
                        fieldLabel: 'RD Size',
                        id: 'prd'
                    }, {
                        fieldLabel: 'LL1 Size',
                        id: 'pll1'
                    }
                    
            ]
            }]
        }]
    });

    var iframe = document.getElementById('gramArea');
    new Ext.Viewport({
    layout : "border",
    items : [      {
        region : "center",
        items : [metrics,metricsPred]
        
    },      {
        region : "north",
        title : "Toolbar",
        height : 60,
        items :[ tb ]
    } ,{
        region : "west",
        title : "Grammar",
        width : 739,
        items : [iframe]
        }
    ]
    });
});


